#!/bin/bash
####### script-name.sh #######

MUGSYBACK_CONF="/etc/mugsyback.conf"

main()
# Purpose:	main execution script
{
	####### command line arguments
	while getopts "c:del" o ; do
        	case "$o" in

                	c)      MUGSYBACK_CONF="${OPTARG}" ;;
                	d)      logLevel=debug ;;
                	e)      enableEmail=1 ;;
                	l)      logToStandardOut=-s ;;
                	:)      echo "Option -${OPTARG} requires an argument." ; exit 1 ;;
                	*)      usageAndBail ;;
        	esac
	done

	# get global script vars (local to main only)
	eval $(sed -e '/^ *#/d;s/#.*//' -e '/^$/d' -e "0,/\[globalScriptVariables\]/d" -e "/\[.*\]/,\$d" -e 's/^/local /' ${MUGSYBACK_CONF})
       	local backupSourceList="$(grep "\[backupSource[0-99]\]" ${MUGSYBACK_CONF} | tr -d '[]')"

	#  
        for i in $(echo ${backupSourceList}) ; do
		# start subshell to keep variables local in each loop
                ( ConfVariables set "${i}"

		if test -z "${DESTINATION}" ; then
			DESTINATION="${GLOBAL_DESTINATION}"
        	fi	       
		if test -z "${LVM_SNAPSHOT}" ; then
			LVM_SNAPSHOT="${GLOBAL_LVM_SNAPSHOT}"
        	fi	       

        	if ( destinationMounted "${DESTINATION}" ) ; then
			local destinationWasMounted="0"
                	echo "${DESTINATION} already mounted"
        	else
                	if ( mountBackupDestination "${DESTINATION}" ) ; then
                        	echo "${DESTINATION} mounted succesfully"
                	else
                        	echo "${DESTINATION} mount failed cannot continue"
				continue
                	fi  
        	fi  

		if test "${LVM_SNAPSHOT}" = "true"; then
			if ( lvmCreateSnapshot ${LVM_VG} ${LVM_NAME} ${LVM_SNAPSHOT_SIZE} ) ; then
				echo "${LVM_NAME} snapshot created succesfully"
				#change path to backup
			else
				echo "${LVM_NAME} snapshot creation failed"
				continue
			fi
		fi
		sleep 10 # delete me
		
		# sript stuff here
		if test "${LVM_SNAPSHOT}" = "true"; then
			if ( lvmRemoveSnapshot ${LVM_VG} ${LVM_NAME} ) ; then
				echo "${LVM_NAME} snapshot removed succesfully"
			else
				echo "${LVM_NAME} snapshot removal failed"
			fi
		fi
		# Unset path varaible for lvm


		### more script stuff here

		if test -z "${destinationWasMounted}" ; then
        		if ( umountBackupDestination "${DESTINATION}" ) ; then
                		echo "${DESTINATION} un-mounted succesfully"
        		else
                		echo "${DESTINATION} un-mount failed"
        		fi
		else
			echo "${DESTINATION} left mounted as it was already mounted"
		fi

		ConfVariables unset "${i}" )
	done
}

destinationMounted()
# Purpose:      check if backup destination is already mounted
#               $1 = Backup Destination mounted via /etc/fstab
{
        local backupDestination="$1" ; shift
        test "$(grep "${backupDestination}" /etc/mtab)" && return 0 || return 1
}

mountBackupDestination()
# Purpose:      mount backup destination
#               $1 = Backup Destination mounted via /etc/fstab
{
        local backupDestination="$1" ; shift 
        syncDisks ; mount "${backupDestination}" && return 0 || return 1
}

umountBackupDestination()
# Purpose:      un-mount backup destination
#               $1 = Backup Destination mounted via /etc/fstab
{
        local backupDestination="$1" ; shift 
        syncDisks ; umount "${backupDestination}" && return 0 || return 1
}

syncDisks()
# Purpose:	force changed blocks to disk
{
	cd /
	sync &
	wait
}

checkBackupDestination()
# Purpose:      check backup destination is prepared
#               $1 = Backup Destination
#               $2 = Backup Directory in root of Backup Destination
#               $3 = Check File in Backup Directory
{           
        local backupDestination="${1}" ; shift
        local backupDir="${1}" ; shift
        local checkFile="${1}" ; shift
        test -f ${backupDestination}/${backupDir}/${checkFile} && return 0 || return 1
}

ConfVariables()
# Purpose:	obtain variables for backup source from config file 
#		$1 = Backup source number i.e. "backupSource2"
#		$2 = set or unset variables from backup source
{
        local o="${1}" ; shift
        local backupSourceNum="${1}" ; shift

	case "${o}" in
		set)	eval $(sed -e '/^ *#/d;s/#.*//' -e '/^$/d' -e "0,/\[${backupSourceNum}\]/d" -e "/\[.*\]/,\$d" ${MUGSYBACK_CONF}) ;;
		unset)	eval $(sed -e '/^ *#/d;s/#.*//' -e '/^$/d' -e "0,/\[${backupSourceNum}\]/d" -e "/\[.*\]/,\$d" ${MUGSYBACK_CONF} | awk -F"=" '{print "unset"" "$1}') ;;
	esac
}

lvmCreateSnapshot()
#Purpose:	create lvm snapshot
#		$1 = lvm volume group
#		$2 = lvm volume name to create snapshot of
#		$3 = lvm shapshot size in %
{
	local vg="${1}" ; shift
	local name="${1}" ; shift
	local size="${1}" ; shift
	local snapName="${name}-snapshot"
	syncDisks ; lvcreate -s -l +${size}FREE -n ${snapName} ${vg}/${name} && return 0 || return 1
}

lvmRemoveSnapshot()
#Purpose:	remove lvm Snapshot
#		$1 = lvm volume group
#		$2 = lvm volume name to remove snapshot of
{
	local vg="${1}" ; shift
	local name="${1}" ; shift
	local snapName="${name}-snapshot"
	syncDisks ; lvremove --force ${vg}/${snapName} && return 0 || return 1
}

####### 

# new logger
# echo "\"${backupDestination}\" already mounted, continuing to test
# backup destination" ;
#               sysLogger "debug" "check file found, continuing..."
#               else sysLogger "critical" "check file not found, prepare the media by creating \"/${backupDir}\" and place \"${checkFile}\" in it."
#               errorLevel "fail" ; cleanup

#backup_using_rsync_remote()
#{
#
#}

###### start script

main $@


####### END #######

